package com.online_exam.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.online_exam.base.RestResponse;
import com.online_exam.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        RestResponse restResponse;
        if (true){
            return true;
        }
        DecodedJWT decode = JWT.decode(token);
        System.out.println(decode.getClaim("id"));
        try {
            DecodedJWT verify = JwtUtil.verify(token);

//            System.out.println(verify.getClaim("username").asString());
            return true;
        } catch (SignatureVerificationException e) {
            restResponse = new RestResponse(401, "无效签名！");
            e.printStackTrace();
        } catch (TokenExpiredException e){
            restResponse = new RestResponse(401, "token过期！");
        } catch (AlgorithmMismatchException e){
            restResponse = new RestResponse(401, "token算法不一致！");
        } catch (Exception e){
            restResponse = new RestResponse(401, "token无效！");
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(JSON.toJSONString(restResponse));
        return false;
    }
}
